package com.study.service;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@Slf4j
@Service
public class NacosClientService {

    private final DiscoveryClient discoveryClient;

    public NacosClientService(DiscoveryClient discoveryClient){
        this.discoveryClient = discoveryClient;
    }

    /**
     * 打印 nacos client 信息到日志中
     * @param serviceId
     * @return
     */
    public List<ServiceInstance> getNacosClientInfo(String serviceId){

        //throw new RuntimeException("has some error");

        log.info("request nacos client to get service instance info: [{}]", serviceId);

        return discoveryClient.getInstances(serviceId);
    }

    /**
     * 提供给编程方式的 hystrix 的请求合并
     */
    public List<List<ServiceInstance>> getNacosClientInfos(List<String> serviceIds){
        log.info("request nacos client to get service infos: [{}]",
                JSON.toJSONString(serviceIds));
        List<List<ServiceInstance>> result = new ArrayList<>();
        serviceIds.forEach(s -> {
            result.add(discoveryClient.getInstances(s));
        });
        return result;
    }

    /**
     * 使用注解形式 实现hystrix请求合并
     */
    @HystrixCollapser(
            batchMethod = "findNacosClientInfos",
            scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
            collapserProperties = {
                    @HystrixProperty(name = "withTimerDelayInMilliseconds",value = "300")
            }
    )
    public Future<List<ServiceInstance>> findNacosClientInfo(String serviceId){

        //系统运行正常、不会走这个方法
        throw new RuntimeException("this method body should not be executed");

    }

    public List<List<ServiceInstance>> findNacosClientInfos(List<String> serviceIds){

        log.info("coming in find nacos client infos: [{}]",
                JSON.toJSONString(serviceIds));
        return getNacosClientInfos(serviceIds);

    }



}
